#include "StdAfx.h"
#include "DataBase.h"


DataBase::DataBase(void)
{
}

DataBase::~DataBase(void)
{
}

void DataBase::initDatabase()
{
	setState(GameState::WAIT_CLIENTS);
	m_currentPlayer.m_number = -1;
	m_currentPlayer.m_posX = 0;
	m_currentPlayer.m_posY = 0;
	m_currentPlayer.m_type = TypePlayer::NONE;
}


void DataBase::pushBackPlayer(PlayerNetwork player)
{
	m_mutexPlayers.lock();
	m_players.push_back(player);
	m_mutexPlayers.unlock();
}

void DataBase::erasePlayerNumber(int number)
{
	m_mutexPlayers.lock();
	for(int it=0; it < m_players.size(); it++)
	{
		if (m_players[it].m_number == number)
		{
			m_players.erase(m_players.begin() + it);
			break;
		}
	}	
	m_mutexPlayers.unlock();
}

int DataBase::getSizePlayer()
{
	m_mutexPlayers.lock();
	int size = m_players.size();
	m_mutexPlayers.unlock();
	return size;
}

PlayerNetwork	DataBase::getElementAt(int pos)
{
	m_mutexPlayers.lock();
	PlayerNetwork t = m_players[pos];
	m_mutexPlayers.unlock();
	return t;
}

void	DataBase::modifyPlayer(PlayerNetwork p)
{
	m_mutexPlayers.lock();

	bool find = false;
	for(int it=0; it < m_players.size(); it++)
	{
		if (m_players[it].m_number == p.m_number)
		{
			m_players[it].m_posX = p.m_posX;
			m_players[it].m_posY = p.m_posY;
			m_players[it].m_type = p.m_type;
			find = true;
			break;
		}
	}
	if (!find)
	{
		m_players.push_back(p);
	}
	m_mutexPlayers.unlock();
}

GameState	DataBase::getCurrentState()
{
	m_mutexState.lock();
	GameState t = m_state;
	m_mutexState.unlock();
	return t;
}

void	DataBase::setState(GameState ngs)
{
	m_mutexState.lock();
	m_state = ngs;
	m_mutexState.unlock();
}


void		DataBase::setCurrentPlayer(PlayerNetwork p)
{
	m_mutexCurrentPlayer.lock();
	m_currentPlayer.m_posX = p.m_posX;
	m_currentPlayer.m_posY = p.m_posY;
	m_currentPlayer.m_type = p.m_type;
	m_mutexCurrentPlayer.unlock();
}

PlayerNetwork		DataBase::getCurrentPlayer()
{
	m_mutexCurrentPlayer.lock();
	PlayerNetwork p = m_currentPlayer;
	m_mutexCurrentPlayer.unlock();
	return p;
}

int	DataBase::getNumberPlayer()
{
	m_mutexNumberPlayer.lock();
	int t = m_numberPlayer;
	m_mutexNumberPlayer.unlock();
	return t;
}

void	DataBase::setNumberPlayer(int number)
{
	m_mutexNumberPlayer.lock();
	m_numberPlayer = number;
	m_mutexNumberPlayer.unlock();
}

std::string DataBase::getIp()
{
	m_mutexIp.lock();
	std::string t = m_ip;
	m_mutexIp.unlock();
	return t;
}

void	DataBase::setIp(std::string ip)
{
	m_mutexIp.lock();
	m_ip = ip;
	m_mutexIp.unlock();
}

int		DataBase::getPort()
{
	m_mutexPort.lock();
	int t = m_port;
	m_mutexPort.unlock();
	return t;
}

void	DataBase::setPort(int port)
{
	m_mutexPort.lock();
	m_port = port;
	m_mutexPort.unlock();
}